package com.cndongtai.service.weixin;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Service;

import com.cndongtai.util.HttpsUtil;

@Service("weixinService")
public class WeixinService {
	
	private static final String APPID = "wx8ea0976cb78859c5";
	private static final String SECRET = "14ff8a54028689b889959c10ec7ce3ff";
	
	private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
	private static final String USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo";
	
	
	/**
	 * 根据临时code授权码获取access_token
	 * @param code
	 * @return
	 */
	public JSONObject getAccessToken(String code) {
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("appid", APPID);
		params.put("secret", SECRET);
		params.put("code", code);
		params.put("grant_type", "authorization_code");
		
		String rspContent = HttpsUtil.doGet(ACCESS_TOKEN_URL, params);
		System.out.println("rspContent==>"+rspContent);
		
		if(rspContent==null || "".equals(rspContent)) {
			return null;
		}
		
		JSONObject json = JSONObject.fromObject(rspContent);
		
		return json;
	}
	
	/**
	 * 获取用户信息
	 * @param accessToken
	 * @param openid
	 * @return
	 */
	public JSONObject getUserInfo(String accessToken, String openid) {
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("access_token", accessToken);
		params.put("openid", openid);
		
		String rspContent = HttpsUtil.doPost(USERINFO_URL, params);
		System.out.println("rspContent==>"+rspContent);
		
		if(rspContent==null || "".equals(rspContent)) {
			return null;
		}
		
		JSONObject json = JSONObject.fromObject(rspContent);
		
		return json;
		
	}

}
